// window.load = function (path, callback) {
//     require([path], function (md) {
//         if (path.endsWith(".vue")) {
//             require.undef("vue-loader!" + path)
//         } else {
//             require.undef(path)
//         }
//
//         callback && callback(md)
//     })
// }

import Vue from 'vue'
import axios from 'axios'
import HeyUI from 'HeyUI'

let ajax = {
    get: function (uri, params) {
        params = params || {};
        return axios.get(uri, {params: params});
    },
    delete: function (uri, params) {
        params = params || {};
        return axios.delete(uri, {params: params});
    },
    put: function (uri, params) {
        params = params || {};
        return axios.put(uri, params);
    },
    post: function (uri, params) {
        params = params || {};
        return axios.post(uri, params);
    },
    formPost: function (uri, params) {
        params = params || {};
        let data = new FormData();
        Object.keys(params).forEach(function (key) {
            let v = params[key];
            if (v == null) {
                return
            }
            if (v.constructor == Array) {
                for (let i = 0; i < v.length; i++) {
                    data.append(key, v[i]);
                }
            } else {
                data.append(key, v);
            }
        });
        return axios.post(uri, data);
    },
    upload: function (uri, params) {
        params = params || {};
        let data = new FormData();
        Object.keys(params).forEach(function (key) {
            let v = params[key];
            if (v == null) {
                return
            }
            if (v.constructor == Array) {
                for (let i = 0; i < v.length; i++) {
                    data.append(key, v[i]);
                }
            } else {
                data.append(key, v);
            }
        });
        return axios({
            url: uri,
            method: 'POST',
            data: data,
            onUploadProgress: function (progressEvent) {
                if (progressEvent.loaded == progressEvent.total) {
                    HeyUI.$Loading.close();
                } else {
                    let complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
                    //console.log('上传 ' + complete)
                    HeyUI.$Loading('文件上传中 ' + complete);
                }
            }
        })//axios.post(uri, data);
    },
    download(path) {
        if (axios.defaults.baseURL) {
            path = axios.defaults.baseURL + path
        }
        let elemIF = document.createElement('iframe')
        elemIF.src = path;
        elemIF.style.display = 'none';
        elemIF.onload = function () {
            document.body.removeChild(elemIF);
        }
        document.body.appendChild(elemIF)
    },
    /**
     * 使用ajax方式下载
     * @param path 路径
     * @param params 参数
     * @param method 请求方法,默认为GET,仅支持post,get
     * @param fileName 文件下载后的名字
     */
    downloadA(path, params = {}, method = 'GET', fileName='') {

        let ap={url: path, method: method, responseType: 'arraybuffer'}
        if(method.toLowerCase()=='get'){
            ap.params=params
        }else{
            ap.data=params
        }

        axios.request(ap).then(resp => {
            if (!fileName) {
                let tempName = resp.headers["content-disposition"];
                if (tempName) {
                    tempName = tempName.split(";")[1].split("filename=")[1];
                    fileName = decodeURI(tempName);
                } else {
                    fileName = "下载文件";
                }
            }
            let data = resp.data
            debugger
            //获取数据流数据
            let blob = new Blob([data]);
            var downloadElement = document.createElement("a");
            var href = window.URL.createObjectURL(blob); //创建下载的链接
            downloadElement.href = href;
            downloadElement.download = fileName; //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement);//下载完成移除元素
            window.URL.revokeObjectURL(href);//释放掉blob对象
        })
    },
    loadModule(path) {//使用require载入模块，包含vue。区别与require的是，该方法不会缓存模块
        return new Promise(resolve => {
            require([path], function (md) {
                if (path.endsWith(".vue")) {
                    require.undef("vue-loader!" + path)
                } else {
                    require.undef(path)
                }
                resolve(md)
            })
        })
    }
}

function dateFormat(fmt, date) {
    var o = {
        "M+": date.getMonth() + 1, //月份
        "d+": date.getDate(), //日
        "h+": date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, //小时
        "H+": date.getHours(), //小时
        "m+": date.getMinutes(), //分
        "s+": date.getSeconds(), //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds() //毫秒
    };
    var week = {
        "0": "/u65e5",
        "1": "/u4e00",
        "2": "/u4e8c",
        "3": "/u4e09",
        "4": "/u56db",
        "5": "/u4e94",
        "6": "/u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[date.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;

}

function formatNumber(num, pattern) {
    var strarr = num ? num.toString().split('.') : ['0'];
    var fmtarr = pattern ? pattern.split('.') : [''];
    var retstr = '';
    // 整数部分
    var str = strarr[0];
    var fmt = fmtarr[0];
    var i = str.length - 1;
    var comma = false;
    for (var f = fmt.length - 1; f >= 0; f--) {
        switch (fmt.substr(f, 1)) {
            case '#':
                if (i >= 0) retstr = str.substr(i--, 1) + retstr;
                break;
            case '0':
                if (i >= 0) retstr = str.substr(i--, 1) + retstr;
                else retstr = '0' + retstr;
                break;
            case ',':
                comma = true;
                retstr = ',' + retstr;
                break;
        }
    }
    if (i >= 0) {
        if (comma) {
            var l = str.length;
            for (; i >= 0; i--) {
                retstr = str.substr(i, 1) + retstr;
                if (i > 0 && ((l - i) % 3) == 0) retstr = ',' + retstr;
            }
        } else retstr = str.substr(0, i + 1) + retstr;
    }
    retstr = retstr + '.';
    // 处理小数部分
    str = strarr.length > 1 ? strarr[1] : '';
    fmt = fmtarr.length > 1 ? fmtarr[1] : '';
    i = 0;
    for (var f = 0; f < fmt.length; f++) {
        switch (fmt.substr(f, 1)) {
            case '#':
                if (i < str.length) retstr += str.substr(i++, 1);
                break;
            case '0':
                if (i < str.length) retstr += str.substr(i++, 1);
                else retstr += '0';
                break;
        }
    }
    return retstr.replace(/^,+/, '').replace(/\.$/, '');
}

let format = function (value, format) {
    if (arguments.length == 2) {
        if (format.startsWith("#") || format.startsWith("0")) {
            return formatNumber(value, format);
        } else {
            if (value == null) {
                return "";
            }
            if (value instanceof Date) {

            } else {
                value = new Date(value);
            }
            return dateFormat(format, value);
        }
    }
    format = value;
    if (format.startsWith("#") || format.startsWith("0")) {
        return function (val) {
            return formatNumber(val, format);
        }
    } else {
        return function (val) {
            if (val == null) {
                return "";
            }
            if (val instanceof Date) {

            } else {
                val = new Date(val);
            }
            return dateFormat(format, val);
        }
    }

}
let DataSource = function (uri, pageable) {
    this.data = [];
    this.params = {};
    this.loading = false;
    this.uri = uri;
    this.method = "post"
    let self = this;
    if (pageable) {
        this.pagination = {
            page: 0,
            size: 10,
            total: 0
        }
    }
    this.param = function (params) {
        Object.assign(self.params, params)
        return this;
    }
    this.setParam = function (name, value) {
        this.params[name] = value;
        return this;
    }
    //数据载入监听
    let listeners = {}
    /**
     * 数据载入监听
     * @param name beforeLoad load error
     * @param fn
     */
    this.on = function (name, fn) {
        if (listeners[name]) {
            listeners[name].push(fn)
        } else {
            listeners[name] = [fn]
        }
    }
    /**
     * 清空数据
     */
    this.clean = function () {
        self.data.splice(0, self.data.length);
        if (self.pagination) {
            self.pagination.total = 0
        }
    }
    /**
     * 把数据放入到data中,不直接通过data赋值,这样vue可以感知到数据变化
     * @param data
     */
    this.putData = function (data) {
        self.data.splice(0, self.data.length);
        self.data.push(...data);
    }
    /**
     *
     * @param data
     * @returns {*}
     */
    this.transform = function(data){
        return data;
    }
    /**
     *
     * @param params 查询参数
     * @param fn 数据转换回调
     * @returns {DataSource}
     */
    this.load = function (params, fn) {
        self.loading = true;
        if (params) {
            if (params instanceof Function) {
                fn = params;
                params = self.params;
            }
        } else {
            params = self.params;
        }
        if (self.pagination) {
            params.pageNo = self.pagination.page;
            params.pageSize = self.pagination.size;
        }
        if (listeners.beforeLoad) {
            for (let fn of listeners.beforeLoad) {
                fn(params)
            }
        }

        ajax[self.method](self.uri, params).then(resp => {
            self.loading = false;
            if (listeners.load) {
                for (let fn of listeners.load) {
                    fn(resp.data)
                }
            }
            if (resp.data) {
                let data = resp.data;
                if(self.transform){
                    data=self.transform(data)
                }
                if (fn) {
                    data = fn(data);
                }
                self.putData(data)
            }
            if (self.pagination) {
                self.pagination.total = resp.total || 0;
            }
        }).catch(e => {
            self.clean()
            if (listeners.error) {
                for (let fn of listeners.error) {
                    fn(e)
                }
            }
        })
        return this;
    }
}

Vue.use(HeyUI)
Vue.prototype.$axios = axios
Vue.prototype.$ajax = ajax
Vue.prototype.$priv = function (code) {
    let store = this.$store || Vue.store
    let user = store.state.user
    if (user.username == 'admin') {
        return true
    }
    let permissions = user.permissions
    if (!permissions) {
        return false
    } else {
        return permissions.indexOf(code) > -1
    }
}
Vue.prototype.$role = function (code) {
    let store = this.$store || Vue.store
    let user = store.state.user
    if (user.username == 'admin') {
        return true
    }
    let roles = localStorage.roles
    if (!roles) {
        return false
    } else {
        return roles.indexOf(code) > -1
    }
}
//权限指令
Vue.mixin({
    props: {
        priv: String,
        role: String
    },
    beforeCreate: function (el, binding) {
        let props = this.$options.propsData
        if (props) {
            let _priv = props.priv
            if (_priv) {
                if (!this.$priv(_priv)) {
                    this.$options = {//没有权限不渲染
                        render: function () {
                        }
                    };
                    return
                }
            }
            let _role = props.role
            if (_role) {
                if (!this.$role(_role)) {
                    this.$options = {//没有权限不渲染
                        render: function (c) {
                        }
                    };
                    return
                }
            }
        }
    }
})
//导入组件
Vue.component('FileInput', function (resolve) {
    require(['coms/FileInput'], resolve)
})
Vue.component('MonacoEditor', function (resolve) {
    require(['coms/MonacoEditor'], resolve)
})
Vue.component('Chart', function (resolve) {
    require(['coms/Echarts'], resolve)
})
Vue.component('RichTextEditor', function (resolve) {
    require(['coms/RichTextEditor'], resolve)
})
HeyUI.$Alert = Vue.prototype.$Alert = function (title, info) {
    return new Promise(resolve => {
        this.$Modal({
            title: title,
            content: info,
            buttons: [{
                type: 'ok',
                name: '确认',
                color: 'primary'
            }],
            events: {
                ok: (modal) => {
                    modal.close();
                    resolve()
                }
            }
        })
    })
}
HeyUI.$Prompt = Vue.prototype.$Prompt = function (title, defaultValue) {
    return new Promise(resolve => {
        this.$Modal({
            component: {
                vue: {
                    data() {
                        return {
                            title: title,
                            value: defaultValue || ''
                        }
                    },
                    methods: {
                        cancel() {
                            this.$emit('close');
                        },
                        success() {
                            if (this.value) {
                                resolve(this.value)
                                this.$emit('close');
                            } else {
                                this.$Message("没有内容")
                            }
                        }
                    },
                    //template: '<div><header class="h-modal-header">{{title}}</header><div style="padding:10px"><input style="width:100%" type="text" v-model="value"/></div><footer class="h-modal-footer"><Button @click="cancel">取消</Button><Button color="primary" @click="success">确认</Button></footer></div>',
                    render: function (_c) {
                        let self = this;
                        return _c('div', [_c('header', {staticClass: "h-modal-header"}, [title]), _c('div', {staticStyle: {"padding": "10px"}}, [_c('input', {
                            directives: [{
                                name: "model",
                                rawName: "v-model",
                                value: (this.value),
                                expression: "value"
                            }],
                            staticStyle: {"width": "100%"},
                            attrs: {"type": "text"},
                            domProps: {"value": (this.value)},
                            on: {
                                input: function ($event) {
                                    if ($event.target.composing) return;
                                    self.value = $event.target.value
                                }
                            }
                        })])
                            , _c('footer', {staticClass: "h-modal-footer"}, [_c('Button', {on: {"click": this.cancel}}, ["取消"]), _c('Button', {
                                attrs: {"color": "primary"},
                                on: {"click": this.success}
                            }, ["确认"])], 1)])
                    }
                }
            }
        })
    })

}
Vue.filter('format', format)
let routed = {}
export default {
    Vue,
    ajax,
    axios,
    util: {
        fields(obj, fields) {
            let ret = {}
            if (obj == null || fields == null) {
                return ret;
            }
            for (let f of fields.split(',')) {
                if (obj.hasOwnProperty(f)) {
                    ret[f] = obj[f]
                }
            }
            return ret;
        },
        fold(obj, fields) {//将对应字段的数组用','拼接
            if (obj == null || fields == null) {
                return obj;
            }
            if (!fields) {
                return obj;
            }
            let result = {};
            Object.assign(result, obj)
            for (let f of fields.split(',')) {
                if (obj[f]) {
                    result[f] = obj[f].join(',')
                }
            }
            return result;
        },
        unfold(obj, fields) {//将对应字段的字符串用','拆封
            if (obj == null || fields == null) {
                return obj;
            }
            if (!fields) {
                return obj;
            }
            let result = {};
            Object.assign(result, obj)
            for (let f of fields.split(',')) {
                if (obj[f]) {
                    result[f] = obj[f].split(',')
                }
            }
            return result;
        },
        mapToKv(data) {
            if (!data) {
                return []
            }
            let r = []
            let keys = Object.keys(data).sort((a, b) => a > b ? 1 : -1);
            for (let k of keys) {
                r.push({key: k, title: data[k]})
            }
            return r;
        },
        clean(value) {//清空数据
            if (value == null) {
                return;
            }
            if (value instanceof Array) {
                value.splice(0, value.length)
            } else {
                Object.keys(value).forEach(k => {
                    let v = value[k]
                    if (v == null) {
                        return
                    }
                    if (v instanceof Array) {
                        v.splice(0, v.length)
                    } else {
                        value[k] = null
                    }
                })
            }
        }
    },
    // framework: framework,
    HeyUI: HeyUI,
    format: format,
    DataSource: DataSource,
    init: function (target, idx, options) {
        if (options && options.baseURL) {
            axios.defaults.baseURL = options.baseURL
        }
        let idxPage = {
            render: function (c) {
                return c('div',
                    {
                        attrs: {
                            id: "app"
                        }
                    }, [c('router-view')], 1)
            }
        }
        Object.assign(idxPage, idx)
        new Vue(idxPage).$mount(target)
        let perLoader = document.getElementById("per-loader");
        if (perLoader) {
            perLoader.style.display = 'none'
        }

    }
}

//组件定义
//define('')
